package com.wyj.email.service;

import com.wyj.email.entity.EmailBO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;

/**
 * TODO:
 *
 * @author wuyijie
 * @date 2022/2/9 23:29
 */
@Component
public class IEmailApiImpl {
    @Value("${spring.mail.username}")
    private String fromAddress;

    private final JavaMailSender javaMailSender;

    public IEmailApiImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    private SimpleMailMessage convertEmailBO(EmailBO emailBO) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject(emailBO.getSubject());
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom(fromAddress);
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        // message.setTo("10*****16@qq.com","12****32*qq.com");
        message.setTo(emailBO.getToAddress());
        // 设置邮件抄送人，可以有多个抄送人
        // message.setCc("12****32*qq.com");
        // 设置隐秘抄送人，可以有多个
        // message.setBcc("7******9@qq.com");
        // 设置邮件发送日期
        LocalDateTime localDateTime = emailBO.getDate();
        if (Objects.isNull(localDateTime)) {
            localDateTime = LocalDateTime.now();
        }
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        message.setSentDate(date);
        // 设置邮件的正文
        message.setText(emailBO.getContent());

        return message;
    }

    public Boolean sendEmail(EmailBO emailBO) {
        try {
            javaMailSender.send(convertEmailBO(emailBO));
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
